package com.example.campuslink.ui.activity.ai


import android.os.Handler
import android.os.Looper
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.Toast
import androidx.lifecycle.lifecycleScope
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.example.campuslink.BR
import com.example.campuslink.R
import com.example.campuslink.commen.http.CompletionRequest
import com.example.campuslink.commen.http.Retrofit
import com.example.campuslink.databinding.ActivityInquiriesBinding
import com.example.campuslink.model.DeepSeekTalkData
import com.example.campuslink.ui.activity.BaseActivity
import com.example.campuslink.viewModel.ai.InquiriesViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class InquiriesActivity : BaseActivity<ActivityInquiriesBinding, InquiriesViewModel>(
    InquiriesViewModel::class.java,
    R.layout.activity_inquiries,
    BR.viewModel
) {
    private var handler: Handler? = null
    private var index = 0
    private var index2 = 0
    private var think = ""
    private var answer = ""
    private var textAnimationRunnable: Runnable? = null
    override fun initView() {
        mViewModel?.context = this
        mViewModel?.initDB(this)
        mViewModel?.getUserInfoTable()
        handler = Handler(Looper.getMainLooper())
        mViewModel?.userInfo?.observe(this) {
            Glide.with(this).load(mViewModel?.userInfo?.value?.userAvatar)
                .error(R.drawable.ic_empty)
                .apply(RequestOptions.circleCropTransform())
                .into(mViewDataBinding?.ivUserImg!!)
        }

        mViewDataBinding?.etUserAsk?.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_SEND) {
                // 获取输入内容并发送请求
                val question = mViewDataBinding?.etUserAsk?.text.toString()
                if (question.isNotBlank()) {
                    sendRequest(question)
                }
                true // 表示已处理该事件
            } else {
                false // 未处理其他动作
            }
        }
        mViewDataBinding?.btnSend?.setOnClickListener {
            // 获取输入内容并发送请求
            val question = mViewDataBinding?.etUserAsk?.text.toString()
            if (question.isNotBlank()) {
                sendRequest(question)
            }
        }
        mViewDataBinding?.tvHistory?.setOnClickListener({
            mViewModel?.jumpToHistory()
        })
        mViewDataBinding?.ivBack?.setOnClickListener({
            finish()
        })
    }

    private fun sendRequest(context: String) {
        mViewDataBinding?.tvUserAsk?.text = context
        mViewDataBinding?.etUserAsk?.text?.clear()
        mViewDataBinding?.tvUserAsk?.visibility = View.VISIBLE
        mViewDataBinding?.ivAiImg?.visibility = View.GONE
        mViewDataBinding?.pbLoad?.visibility = View.VISIBLE
        mViewDataBinding?.tvThink?.text = ""
        mViewDataBinding?.tvAnswer?.text = ""
        // 使用 lifecycleScope 管理协程生命周期
        lifecycleScope.launch {
            try {

                // 发起请求
                val response = Retrofit.instance.createCompletion(CompletionRequest.create(context))

                // 处理成功响应
                withContext(Dispatchers.Main) {
                    mViewDataBinding?.pbLoad?.visibility = View.GONE
                    mViewDataBinding?.ivAiImg?.visibility = View.VISIBLE
                    answer = response.content
                    think = response.reasoning
                    index = 0
                    startTextAnimation()
                    mViewModel?.addAiHistory(DeepSeekTalkData(context, think, answer))
                }
            } catch (e: Exception) {
                withContext(Dispatchers.Main) {
                    val toast = mViewModel?.handleError(e)
                    Toast.makeText(this@InquiriesActivity, toast.toString(), Toast.LENGTH_SHORT)
                        .show()
                    mViewDataBinding?.pbLoad?.visibility = View.GONE
                }
            }
        }
    }

    private fun startTextAnimation() {

        // 清除之前的动画
        stopTextAnimation()

        textAnimationRunnable = Runnable {
            if (index < think.length) {
                mViewDataBinding?.tvThink?.append(think[index].toString())
                index++
                handler?.postDelayed(textAnimationRunnable ?: return@Runnable, 100)  // 递归调用
            } else {
                index2 = 0
                startTextAnimation2()
            }
        }

        handler?.postDelayed(textAnimationRunnable ?: return, 100)
    }

    private fun stopTextAnimation() {
        textAnimationRunnable?.let {
            handler?.removeCallbacks(it)
        }
        index = 0
        index2 = 0
        textAnimationRunnable = null
    }


    private fun startTextAnimation2() {

        textAnimationRunnable = Runnable {
            if (index2 < answer.length) {
                mViewDataBinding?.tvAnswer?.append(answer[index2].toString())
                index2++
                handler?.postDelayed(textAnimationRunnable ?: return@Runnable, 100)  // 递归调用
            }
        }

        handler?.postDelayed(textAnimationRunnable ?: return, 100)
    }


    override fun onDestroy() {
        super.onDestroy()
        textAnimationRunnable?.let {
            handler?.removeCallbacks(it)
        }
        textAnimationRunnable = null
        handler?.removeCallbacksAndMessages(null)
    }
}